package com.leal.util;

import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @Classname bigdata
 * @Description TODO
 * @Date 2024/8/20 16:43
 * @Created by leal
 */
public class CommonUtil {
    /**
     * 解析 SELECT 字段信息。
     *
     * @param sql SQL 语句
     * @return 表达式的映射，键为表名或别名，值为对应的字段列表
     */
    public static Map<String, List<String>> parseSelectFields(String sql) {
        Map<String, List<String>> fields = new HashMap<>();
        // 匹配 SELECT 子句中的字段
        String selectPattern = "SELECT\\s+(.*)\\s+FROM";
        Pattern pattern = Pattern.compile(selectPattern, Pattern.CASE_INSENSITIVE);
        Matcher matcher = pattern.matcher(sql);

        if (matcher.find()) {
            String selectClause = matcher.group(1);
            // 分割字段表达式
            String[] expressions = selectClause.split(",\\s*");
            for (String expr : expressions) {
                parseExpression(expr.trim(), fields);
            }
        }
        return fields;
    }

    /**
     * 解析单个字段表达式。
     *
     * @param expression 字段表达式
     * @param fields     字段映射
     */
    private static void parseExpression(String expression, Map<String, List<String>> fields) {
        // 匹配表名或别名
        String tablePattern = "(\\w+)\\.(\\w+)";
        Pattern tablePatternCompiled = Pattern.compile(tablePattern, Pattern.CASE_INSENSITIVE);
        Matcher tableMatcher = tablePatternCompiled.matcher(expression);

        if (tableMatcher.find()) {
            String tableNameOrAlias = tableMatcher.group(1);
            String columnName = tableMatcher.group(2);
            fields.computeIfAbsent(tableNameOrAlias, k -> new ArrayList<>()).add(columnName);
        } else if ("*".equalsIgnoreCase(expression)) {
            // 处理通配符情况
            String tablePatternForAllColumns = "(\\w+)\\.*";
            Pattern tablePatternForAllColumnsCompiled = Pattern.compile(tablePatternForAllColumns, Pattern.CASE_INSENSITIVE);
            Matcher tableMatcherForAllColumns = tablePatternForAllColumnsCompiled.matcher(expression);
            if (tableMatcherForAllColumns.find()) {
                String tableNameOrAlias = tableMatcherForAllColumns.group(1);
                fields.put(tableNameOrAlias, Collections.singletonList("*"));
            }
        } else {
            // 如果没有找到表名，可能是没有别名的情况
            fields.computeIfAbsent("", k -> new ArrayList<>()).add(expression);
        }
    }
}
